package com.potato.base.base;

import com.potato.base.mvp.IModel;
import com.potato.base.mvp.IPresenter;
import com.potato.base.mvp.IView;
import com.potato.base.observer.BaseObserver;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

public abstract class BasePresenter<V extends IView,M extends IModel> implements IPresenter<V>{

    private V mView;
    private M mModel;
    private CompositeDisposable compositeDisposable;

    public BasePresenter(){
        this.mModel =createModel();
    }

    public M getModel(){
        if (mModel==null)
            try {
                throw  new Throwable("当前加载类不需要Presenter");
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        return mModel;
    }

    @Override
    public void attachView(V view) {
        this.mView=view;
    }

    /**
     * 检查View是否存在
     */
    protected boolean isViewAttached() {
        return mView != null;
    }

    @Override
    public void detachView() {
        removeDisposable();
        mView=null;
    }

    public void addDisposable(Observable<?> observable, BaseObserver observer) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(observer));
    }

    public void removeDisposable() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

    public V getIView() {
        if (mView==null)
            return null;
        return mView;
    }


    public abstract M createModel();
}
